<template>
  <el-card shadow="never" class="organizationTree">
    <el-input v-model="catalogName" placeholder="部门名称" clearable>
      <template #prefix>
        <i-ep-search />
      </template>
    </el-input>

    <el-tree
      ref="deptTreeRef"
      class="mt-2"
      :data="deptList"
      :props="{
        children: 'nodes',
        label: 'organizationName',
        disabled: '',
      }"
      :expand-on-click-node="false"
      :filter-node-method="handleFilter"
      default-expand-all
      @node-click="handleNodeClick"
    />
  </el-card>
</template>

<script setup lang="ts">
import request from "@/utils/request";

const props = defineProps({
  modelValue: {
    type: [String],
    default: undefined,
  },
});

const deptList = ref<OptionType[]>(); // 目录列表
const deptTreeRef = ref(ElTree); // 目录树
const catalogName = ref(); // 目录名称

const emits = defineEmits(["node-click", "update:modelValue"]);

const departmentId = useVModel(props, "modelValue", emits);

watchEffect(
  () => {
    deptTreeRef.value.filter(catalogName.value);
  },
  {
    flush: "post", // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 目录筛选 */
function handleFilter(value: string, data: any) {
  if (!value) {
    return true;
  }
  return data.organizationName.indexOf(value) !== -1;
}

/** 目录树节点 Click */
function handleNodeClick(data: { [key: string]: any }) {
  departmentId.value = data.id;
  emits("node-click");
}

onBeforeMount(async () => {
  const { data } = await request({
    url: `system/sysOrganization/getUsableTree`,
    method: "post",
    data: {},
  });
  deptList.value = data;
});
</script>

<style lang="scss" scoped>
.organizationTree {
  :deep(.el-card__body) {
    padding: 10px 7px !important;
  }
  :deep(.el-tree-node__content) {
    font-size: 13px;
    .el-tree-node__expand-icon {
      padding: 2px;
      margin-top: -5px;
    }
  }
}
</style>
